// CRM 系统通用工具类

/**
 * 显示通知提示
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型 (success, error, info, warning)
 * @param {number} duration - 显示时长（毫秒）
 */
function showNotification(message, type = 'info', duration = 3000) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 设置样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '80px',
        right: '-400px',
        padding: '15px 25px',
        borderRadius: '6px',
        color: 'white',
        fontWeight: '500',
        zIndex: '9999',
        transition: 'right 0.3s ease',
        boxShadow: '0 5px 15px rgba(0, 0, 0, 0.2)',
        minWidth: '300px'
    });
    
    // 根据类型设置背景色
    if (type === 'success') {
        notification.style.backgroundColor = '#28a745';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#dc3545';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#ffc107';
        notification.style.color = '#212529';
    } else {
        notification.style.backgroundColor = '#17a2b8';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.right = '20px';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.right = '-400px';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, duration);
}

/**
 * 模态框控制类
 */
class Modal {
    constructor(modalId = 'modal') {
        this.modal = document.getElementById(modalId);
        if (!this.modal) {
            console.error('未找到指定的模态框元素');
            return;
        }
        
        this.modalTitle = this.modal.querySelector('#modalTitle');
        this.modalBody = this.modal.querySelector('.modal-body');
        this.confirmBtn = this.modal.querySelector('.modal-btn.confirm');
        this.cancelBtn = this.modal.querySelector('.modal-btn.cancel');
        this.closeBtn = this.modal.querySelector('.close-modal-btn');
        
        this.initEvents();
    }
    
    initEvents() {
        // 关闭按钮事件
        this.closeBtn.addEventListener('click', () => this.hide());
        this.cancelBtn.addEventListener('click', () => this.hide());
        
        // 点击外部关闭
        this.modal.addEventListener('click', (e) => {
            if (e.target === this.modal) {
                this.hide();
            }
        });
    }
    
    /**
     * 显示模态框
     * @param {string} title - 模态框标题
     * @param {string|HTMLElement} content - 模态框内容
     * @param {Function} confirmCallback - 确认按钮回调函数
     */
    show(title, content, confirmCallback = null) {
        if (this.modalTitle) this.modalTitle.textContent = title;
        
        if (this.modalBody) {
            // 清空现有内容
            this.modalBody.innerHTML = '';
            
            // 添加新内容
            if (typeof content === 'string') {
                this.modalBody.innerHTML = content;
            } else if (content instanceof HTMLElement) {
                this.modalBody.appendChild(content);
            }
        }
        
        // 设置确认回调
        if (this.confirmBtn) {
            this.confirmBtn.onclick = () => {
                if (confirmCallback) {
                    confirmCallback();
                }
                this.hide();
            };
        }
        
        // 显示模态框
        this.modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    
    /**
     * 隐藏模态框
     */
    hide() {
        this.modal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

/**
 * 日期格式化函数
 * @param {Date} date - 日期对象
 * @param {string} format - 格式化字符串
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(date, format = 'YYYY-MM-DD') {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    
    return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
}

/**
 * 格式化货币
 * @param {number} amount - 金额
 * @param {string} currency - 货币符号
 * @returns {string} 格式化后的货币字符串
 */
function formatCurrency(amount, currency = '¥') {
    return `${currency}${parseFloat(amount).toLocaleString(undefined, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 2
    })}`;
}

/**
 * 获取相对时间
 * @param {Date} date - 日期对象
 * @returns {string} 相对时间描述
 */
function getRelativeTime(date) {
    const now = new Date();
    const diff = now - new Date(date);
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    const week = 7 * day;
    const month = 30 * day;
    const year = 365 * day;
    
    if (diff < minute) {
        return '刚刚';
    } else if (diff < hour) {
        return `${Math.floor(diff / minute)}分钟前`;
    } else if (diff < day) {
        return `${Math.floor(diff / hour)}小时前`;
    } else if (diff < week) {
        return `${Math.floor(diff / day)}天前`;
    } else if (diff < month) {
        return `${Math.floor(diff / week)}周前`;
    } else if (diff < year) {
        return `${Math.floor(diff / month)}个月前`;
    } else {
        return `${Math.floor(diff / year)}年前`;
    }
}

/**
 * 本地存储工具类
 */
class LocalStorageManager {
    /**
     * 保存数据到本地存储
     * @param {string} key - 键名
     * @param {*} value - 值（将被JSON序列化）
     */
    static setItem(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
            return true;
        } catch (e) {
            console.error('保存到本地存储失败:', e);
            return false;
        }
    }
    
    /**
     * 从本地存储获取数据
     * @param {string} key - 键名
     * @param {*} defaultValue - 默认值
     * @returns {*} 解析后的数据或默认值
     */
    static getItem(key, defaultValue = null) {
        try {
            const value = localStorage.getItem(key);
            return value === null ? defaultValue : JSON.parse(value);
        } catch (e) {
            console.error('从本地存储获取数据失败:', e);
            return defaultValue;
        }
    }
    
    /**
     * 从本地存储删除数据
     * @param {string} key - 键名
     */
    static removeItem(key) {
        try {
            localStorage.removeItem(key);
            return true;
        } catch (e) {
            console.error('从本地存储删除数据失败:', e);
            return false;
        }
    }
    
    /**
     * 清空所有本地存储数据
     */
    static clear() {
        try {
            localStorage.clear();
            return true;
        } catch (e) {
            console.error('清空本地存储失败:', e);
            return false;
        }
    }
}

/**
 * 表格排序功能
 * @param {HTMLTableElement} table - 表格元素
 * @param {number} columnIndex - 列索引
 * @param {boolean} ascending - 是否升序
 */
function sortTable(table, columnIndex, ascending = true) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    // 排序行
    rows.sort((a, b) => {
        const aValue = a.cells[columnIndex].textContent.trim();
        const bValue = b.cells[columnIndex].textContent.trim();
        
        // 尝试数字比较
        const aNum = parseFloat(aValue.replace(/[^\d.-]/g, ''));
        const bNum = parseFloat(bValue.replace(/[^\d.-]/g, ''));
        
        if (!isNaN(aNum) && !isNaN(bNum)) {
            return ascending ? aNum - bNum : bNum - aNum;
        }
        
        // 字符串比较
        return ascending 
            ? aValue.localeCompare(bValue)
            : bValue.localeCompare(aValue);
    });
    
    // 重新添加行
    rows.forEach(row => tbody.appendChild(row));
    
    // 更新排序图标
    const headers = table.querySelectorAll('th');
    headers.forEach((header, index) => {
        const icon = header.querySelector('i');
        if (icon) {
            header.removeChild(icon);
        }
        
        if (index === columnIndex) {
            const newIcon = document.createElement('i');
            newIcon.className = ascending ? 'fas fa-sort-up' : 'fas fa-sort-down';
            newIcon.style.marginLeft = '5px';
            header.appendChild(newIcon);
        } else {
            const newIcon = document.createElement('i');
            newIcon.className = 'fas fa-sort';
            newIcon.style.marginLeft = '5px';
            header.appendChild(newIcon);
        }
    });
}

// 将工具函数暴露为全局函数，以便其他脚本可以直接访问
window.showNotification = showNotification;
window.Modal = Modal;
window.formatDate = formatDate;
window.formatCurrency = formatCurrency;
window.getRelativeTime = getRelativeTime;
window.LocalStorageManager = LocalStorageManager;
window.sortTable = sortTable;